import React, { useEffect, useState } from 'react';
import { useAuth } from '../context/AuthContext';

export default function Department() {
  const { user } = useAuth();
  const [departments, setDepartments] = useState([]);
  const [departmentId, setDepartmentId] = useState('');
  const [name, setName] = useState('');

  const fetchDepartments = async () => {
    const res = await fetch('/api/department');
    const data = await res.json();
    if (data.success) setDepartments(data.data);
  };

  useEffect(() => {
    fetchDepartments();
  }, []);

  const handleAdd = async (e) => {
    e.preventDefault();
    if (!departmentId || !name) {
      alert('请填写完整信息');
      return;
    }
    const res = await fetch('/api/department', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ department_id: departmentId, name, _user: user })
    });
    const data = await res.json();
    if (data.success) {
      setDepartmentId('');
      setName('');
      fetchDepartments();
    } else {
      alert(data.message || '添加失败');
    }
  };

  return (
    <div className="card">
      <h2>院系管理</h2>
      {user && user.is_admin ? (
        <form onSubmit={handleAdd} style={{ marginBottom: 20, display: 'flex', gap: 12 }}>
          <input type="text" placeholder="院系编号" value={departmentId} onChange={e => setDepartmentId(e.target.value)} />
          <input type="text" placeholder="院系名称" value={name} onChange={e => setName(e.target.value)} />
          <button type="submit">添加院系</button>
        </form>
      ) : null}
      <table style={{ marginTop: user && user.is_admin ? 0 : 20 }}>
        <thead>
          <tr><th>院系编号</th><th>院系名称</th></tr>
        </thead>
        <tbody>
          {departments && departments.length === 0 ? (
            <tr><td colSpan={2} style={{ textAlign: 'center', color: '#888' }}>暂无院系</td></tr>
          ) : (
            departments.map(dep => (
              <tr key={dep.department_id}>
                <td>{dep.department_id}</td>
                <td>{dep.name}</td>
              </tr>
            ))
          )}
        </tbody>
      </table>
    </div>
  );
} 